package com.zb.uniman.filter;

import com.zb.uniman.mapper.SysUserMapper;
import com.zb.uniman.model.LoginUser;
import com.zb.uniman.model.SysUser;
import com.zb.uniman.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private SysUserMapper userMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");

        if (!StringUtils.hasText(token)) {
            //放行
            System.out.println("没有token");
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //根据redisKey  从redis中获取用户信息  。我不这么弄了，还得整redis。我就手动封装权限permissions。这样方便测试
        String redisKey = "login:" + userid;
//        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        SysUser user = userMapper.selectById(userid);

      List<String> list = new ArrayList<>(Arrays.asList("test","admin"));
//      todo 这里对应LoginService中的loginUser存入redis的代码
        LoginUser loginUser = new LoginUser(user,list);


        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        // 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        System.err.println("JwtAuthenticationTokenFilter中:   "+"过滤器拦截token，loginUser存入authenticationToken（authentication对象），SecurityContextHolder成功");
        //放行
        filterChain.doFilter(request, response);
    }
}
